var fs = require("fs");
var path = require("path");
var Tools = require("./tools");

class MapFileModel{
    constructor(jsonPath){
        // this.jsonData = json;
        let configJson = fs.readFileSync(jsonPath);
        this.json = JSON.parse(configJson);
        this.jsonPath = jsonPath;
        this.fromDir = this.json.fromDir;
        this.toDir = this.json.toDir;
        this.prefix = this.json.prefix;
        this.autoFill = this.json.autoFill;
        this.init();
    }

    init(){
        console.log("图片输出目录：", this.toDir)
        console.log("图片输入目录：", this.fromDir);

        let temp = Tools.getFilesPathRecursion(this.fromDir)

        let mapListName = [];
        let fromPath = path.normalize(this.fromDir + "/");
        console.log("fromPath:", fromPath, temp);

        for(let t of temp){
            let l1 = t.slice(fromPath.length)
            mapListName.push(l1);
            let l2 = l1.split(".")[0];
        }
        
        this.json.mapList = new Map(this.json.mapList);
        this.mergeList(this.json.mapList, mapListName);
        this.json.mapList = Array.from(this.json.mapList);
        fs.writeFileSync(this.jsonPath, JSON.stringify(this.json, null, "\t"))
    }

    mergeList(map, mapKeysArr){
        console.log(map)
        for(let i = 0, len = mapKeysArr.length; i < len; i++){
            let key = mapKeysArr[i]
            if (map.has(key)){
                Tools.copyFile(this.fromDir + "/" + key, this.toDir + "/" + map.get(key) + "." + key.split(".")[1])
            }
            else{
                if (this.autoFill){
                    map.set(key, this.prefix + key.split(".")[0])
                }
                else{
                    map.set(key, "")
                }
            }
        }
    }
}

module.exports = MapFileModel;